<?php
/**
 * lsys orm
 * @author     Lonely <shan.liu@msn.com>
 * @copyright  (c) 2017 Lonely <shan.liu@msn.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0
 */

namespace LSYS\ORM;
use LSYS\Database;
class Transaction {
	/**
	 * @var Database[]
	 */
	protected $_db=array();
	/**
	 * add transction
	 * @param Database $db
	 * @return \LSYS\ORM\Transaction
	 */
	public function add_transaction(Database $db){
		$objid=spl_object_hash($db);
		if (isset($this->_db[$objid]))return $this;
		$this->_db[$objid]=$db;
		return $this;
	}
	/**
	 * begin transction
	 * @param Database $db
	 * @return \LSYS\ORM\Transaction
	 */
	public function begin_transaction(){
		foreach ($this->_db as $db){
			if(!$db->in_transaction())$db->begin_transaction();
		}
		return $this;
	}
	/**
	 *  orm commit
	 */
	public static function commit() {
		foreach ($this->_db as $db){
			if($db->in_transaction())$db->commit();
		}
		$this->_db=array();
		return $this;
	}
	/**
	 * orm rollback
	 */
	public static function rollback() {
		foreach ($this->_db as $db){
			$db->rollback();
		}
		$this->_db=array();
		return $this;
	}
}